package com.ssy.lingxi.workflow.handler.converter;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.workflow.model.bo.MemberRoleBO;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.List;

/**
 * 数据库jsonb字段与 List<MemberRoleBO>转换
 * @author 万宁
 * @version 2.0.0
 * @date 2020-11-19
 */
@Converter
public class JpaJsonToMemberRoleBOConverter implements AttributeConverter<List<MemberRoleBO>, String> {
    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public JpaJsonToMemberRoleBOConverter() {
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Override
    public String convertToDatabaseColumn(List<MemberRoleBO> attribute) {
        try {
            return OBJECT_MAPPER.writeValueAsString(attribute);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR, "List<MemberRoleBO>转数据库jsonb字段错误");
        }
    }

    @Override
    public List<MemberRoleBO> convertToEntityAttribute(String dbData) {
        try {
            return OBJECT_MAPPER.readValue(dbData, new TypeReference<List<MemberRoleBO>>() {});
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR, "数据库jsonb字段转List<MemberRoleBO>错误");
        }
    }
}
